<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 商品规格表
 *
 * @icon fa fa-circle-o
 */
class Spec extends Backend
{
 
	protected $relationSearch = true;
	
    /**
     * Spec模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Spec');

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
	
	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax())
		{
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('pkey_name'))
			{
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,true);
			
			
			$total = $this->model
				->with('category')
				->where($where)
				->order($sort, $order)
				->count();
			
			$list = $this->model
				->with('category')
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
			
			$list = collection($list)->toArray();
			$result = array("total" => $total, "rows" => $list);
			
			return json($result);
		}
		return $this->view->fetch();
	}
	
	/**
	 * 添加
	 */
	public function add()
	{
		if ($this->request->isPost())
		{
			$params = $this->request->post("row/a");
			if ($params)
			{
				$values = $params['values'];
				if(!$values){
					$this->error('可选值不能为空');
				}
				
				
				if ($this->dataLimit && $this->dataLimitFieldAutoFill)
				{
					$params[$this->dataLimitField] = $this->auth->id;
				}
				
				Db::startTrans();
				try
				{
					//是否采用模型验证
					if ($this->modelValidate)
					{
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
						$this->model->validate($validate);
					}
					$result = $this->model->allowField(true)->save($params);
					if ($result == false)
					{
						throw new Exception($this->model->getError());
					}
					
					$specId = $this->model->getLastInsID();
					
					if(!$this->model->addItem($specId,$values)){
						throw new Exception('添加选项值出错');
					}
					
					Db::commit();
					$this->success();
				}
				catch (\think\exception\PDOException $e)
				{
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		
		$cateModel = new \app\common\model\GoodsCategory();
		return $this->view->fetch('add',[
			'categorys' => $cateModel->getTreeCategory(),
		]);
	}
	
	
	/**
	 * 编辑
	 */
	public function edit($ids = NULL)
	{
		$row = $this->model->get($ids);
		if (!$row)
			$this->error(__('No Results were found'));
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds))
		{
			if (!in_array($row[$this->dataLimitField], $adminIds))
			{
				$this->error(__('You have no permission'));
			}
		}
		if ($this->request->isPost())
		{
			$params = $this->request->post("row/a");
			if ($params)
			{
				$values = $params['values'];
				unset($params['values']);
				if(!$values){
					$this->error('可选值不能为空');
				}
				
				Db::startTrans();
				try
				{
					//是否采用模型验证
					if ($this->modelValidate)
					{
						$name = basename(str_replace('\\', '/', get_class($this->model)));
						$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
						$row->validate($validate);
					}
					
					$result = $row->allowField(true)->save($params);
					if ($result === false){
						throw new Exception($this->model->getError());
					}
					
					if(!$this->model->addItem($ids,$values,2)){
						throw new Exception('添加选项值出错');
					}
					
					Db::commit();
					$this->success();
				}
				catch (\think\exception\PDOException $e)
				{
					Db::rollback();
					$this->error($e->getMessage());
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		
		$values = Db::name('specItem')->where(['spec_id' => $ids])->select();
		$val = '';
		if($values){
			foreach($values as $value){
				$vals[] = $value['name'];
			}
			$val = implode(';', $vals);
		}
		
		$this->view->assign("values", $val);
		$this->view->assign("row", $row);
		$cateModel = new \app\common\model\GoodsCategory();
		return $this->view->fetch('edit',[
			'categorys' => $cateModel->getTreeCategory()
		]);
	}
	
	
	/**
	 * 获取商品规格
	 */
	public function getCategorySpec(){
		$cid = input('post.cid');
		$goodsId = input('post.goods_id');
		
		$selectIds = [];
		if($goodsId){
			//查找选中规格值
			$specItmes = Db::name('goodsSpecPrice')->where(['goods_id' => $goodsId])->column('key','id');
			if($specItmes){
				foreach ($specItmes as $itme){
					$arr = explode('_',$itme);
					$selectIds = array_merge($selectIds, $arr);
				}
				$selectIds = array_unique($selectIds);
			}
		}
		$specs = Db::name('spec')
			->where(['category_id' => $cid])
			->field('id,name')
			->select();
		$specArr = [];
		if($specs){
			$ids = [];
			foreach ($specs as $spec){
				$ids[] = $spec['id'];
				$spec['items'] = [];
				$specArr[$spec['id']] = $spec;
			}
			
			if($ids){
				$itmes = Db::name('specItem')
					->where(['spec_id'=>['in',$ids]])
					->field('id,name,spec_id')
					->select();
				if($itmes){
					foreach($itmes as $item){
						if(in_array($item['id'], $selectIds)){
							$item['selected'] = true;
						} else {
							$item['selected'] = false;
						}
						$specArr[$item['spec_id']]['items'][] = $item;
					}
				}
			}
		}
		$this->success('查询成功','',array_values($specArr));
	}
	
	/**
	 * 删除
	 */
	public function del($ids = "")
	{
		if ($ids)
		{
			
			Db::startTrans();
			$ids = explode(',',$ids);
			$specRes = $this->model->where(['id' => ['in',$ids]])->delete();
			if(!$specRes){
				Db::rollback();
				$this->error('删除出错');
			}
			
			$itemRes = Db::name('specItem')->where(['spec_id' =>[ 'in', $ids]])->delete();
			if($itemRes !== false){
				Db::commit();
				$this->success();
			} else {
				Db::rollback();
				$this->error('删除出错');
			}
			$pk = $this->model->getPk();
			$adminIds = $this->getDataLimitAdminIds();
			if (is_array($adminIds))
			{
				$count = $this->model->where($this->dataLimitField, 'in', $adminIds);
			}
			$list = $this->model->where($pk, 'in', $ids)->select();
			$count = 0;
			foreach ($list as $k => $v)
			{
				$count += $v->delete();
				Db::name('specItme')->where(['spec_id' => $v->idk])->delete();
			}
			if ($count)
			{
				$this->success();
			}
			else
			{
				$this->error(__('No rows were deleted'));
			}
		}
		$this->error(__('Parameter %s can not be empty', 'ids'));
	}
	
	/**
	 * 计算规格输入框
	 */
	public function getSpecInput(){
		$ids = input('post.ids');
		$goodsIds = input('post.goods_id');
		if(!$ids){
			$this->error('请选择规格');
		}
		
		$checkSpec = [];
		if($goodsIds && $goodsIds > 0){
			$specPrice = Db::name('goodsSpecPrice')->where(['goods_id' => $goodsIds])->select();
			if($specPrice){
				foreach ($specPrice as $v){
					$checkSpec[$v['key']] = $v;
				}
			}
		}
		$ids = explode(',',$ids);
		
		$items = Db::name('specItem')->alias('i')
			->join('spec s', 'i.spec_id = s.id', 'left')
			->where(['i.id' => ['in', $ids]])
			->field('i.id,i.spec_id,i.name, s.name as spec_name')
			->select();
		
		$specArr = [];
		$title = [];
		if($items) {
			foreach($items as $item){
				$specArr[$item['spec_id']][] = $item['id'];
				$title[$item['spec_id']] = $item['spec_name'];
				$newItems[$item['id']] = $item;
			}
		}
		$data = $this->model->getInputArray($specArr, $title);
		$return = [];
		foreach($data['items'] as $item){
			$names = [];
			$keyName = [];
			foreach($item as $v){
				$names[] = $newItems[$v]['name'];
				$keyName[] = $newItems[$v]['spec_name'].':'.$newItems[$v]['name'];
			}
			sort($item);
			$key = implode('_', $item);
			$return[] = [
				'names' => $names,
				'key' => $key,
				'spec_name' => implode(' ',$keyName),
				'price' => isset($checkSpec[$key])?$checkSpec[$key]['price']:0,
				'store_count' => isset($checkSpec[$key])?$checkSpec[$key]['store_count']:0,
				'sku' => isset($checkSpec[$key])?$checkSpec[$key]['sku']:0,
				'id' => isset($checkSpec[$key])?$checkSpec[$key]['id']:'',
			];
		}
		$this->success('处理成功','',['title' => array_values($data['title']), 'items' => $return]);
	}
	
	
	
	/**
	 * 删除规格价格
	 */
	public function delSpecPrice(){
		$id = input('post.id','','int');
		if($id){
			$res = Db::name('goodsSpecPrice')->where(['id' => $id])->delete();
			if($res){
				$this->success();
			} else {
				$this->error('删除出错');
			}
		}
	}
}
